﻿Shader "Unlit/Bloom"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Bloom("Bloom(RGB)",2D) = "black"{}
        _LuminanceThreshold("LuminanceThreshold（亮度阈值）",Float) = 0.5
        _BlurSize("BlurSize（模糊程度）",Float) = 1.0
    }
    SubShader
    {
        CGINCLUDE
            sampler2D _MainTex;
            half4 _MainTex_TexelSize;
            sampler2D _Bloom;
            float _LuminanceThreshold;
            float _BlurSize;

            //---------- ExtractBright ----------//
            struct a2v
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
            };
            struct v2f
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
            };
            //提取亮部区域（vert）
            v2f vertExtractBright(a2v v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.texcoord;
                return o;
            }
            //计算亮度（饱和度为0的颜色值）
            fixed Luminance(fixed4 color) 
            {
                return 0.2125 * color.r + 0.7154 * color.g + 0.0721 * color.b;
            }
            //提取亮部区域（frag）
            fixed4 fragExtractBright(v2f i):SV_Target
            {
                fixed4 col = tex2D(_MainTex,i.uv);
                fixed value = clamp(Luminance(col) - _LuminanceThreshold , 0.0 , 1.0);
                return col * value;
            }
            //---------- Bloom ----------//
            struct v2fBloom
            {
                float4 pos : SV_POSITION;
                half4 uv : TEXCOORD0;
            };
            //Bloom（vert）
            v2fBloom vertBloom(a2v v) 
            {
                v2fBloom o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv.xy = v.texcoord; //_MainTex 的 UV
                o.uv.zw = v.texcoord; //Bloom 的 UV

                #if UNITY_UV_STARTS_AT_TOP //处理平台差异
                if(_MainTex_TexelSize.y < 0.0)
                    o.uv.w = 1.0 - o.uv.w;
                #endif

                return o;
            }
            //Bloom（frag）
            fixed4 fragBloom(v2fBloom i):SV_Target
            {
                return tex2D(_MainTex,i.uv.xy) + tex2D(_Bloom,i.uv.zw); //叠加
            }
        ENDCG

        Tags { "RenderType"="Opaque" }
        LOD 100
        ZTest Always Cull Off ZWrite Off

        Pass //ExtractBright 提取亮部
        {
            CGPROGRAM
            #pragma vertex vertExtractBright
            #pragma fragment fragExtractBright
            ENDCG
        }
        UsePass "Unlit/GaussianBlur/GAUSSIAN_BLUR_VERTICAL" //亮部模糊
        UsePass "Unlit/GaussianBlur/GAUSSIAN_BLUR_HORIZONTAL"
        Pass //Bloom
        {
            CGPROGRAM
            #pragma vertex vertBloom
            #pragma fragment fragBloom
            ENDCG
        }
    }
}
